using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace LocalOverride.Fiddler.UI
{
    public class LoggingPresenter
    {
        private readonly ILoggingView view;
        private readonly Queue<string> messages = new Queue<string>();

        public LoggingPresenter(ILoggingView view, ILogger logger)
        {
            this.view = view;
            logger.NewMessage += LoggerNewMessage;
        }

        private readonly object syncObject = new object();
        void LoggerNewMessage(object sender, NewMessageEventArgs e)
        {
            var currentMessage = new StringBuilder();

            lock (syncObject)
            {
                messages.Enqueue(e.Message);

                if (messages.Count > 1000)
                {
                    messages.Dequeue();
                }

                foreach (var message in messages)
                {
                    currentMessage.AppendLine(message);
                }    
            }
            
            view.LogMessages = currentMessage.ToString();
        }
    }
}